# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:zzly
@file:serializers.py
@time:2020/09/08
"""
from rest_framework import serializers
from apps.article.models import Article
from apps.member.comments.models import Comment
from apps.member.comments.serializers import CommentArticleAppSerializer
from apps.member.models import MemberRecord
from apps.member.serializers import MemeberInfoAppSerializer


class ArticleAppSeializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField(read_only=True)
    tags = serializers.SerializerMethodField()

    def get_tags(self, obj):
        return obj.tags.split('|')

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = Article
        fields = ('id', 'title', 'describe', 'thumbnail', 'tags', 'brown_count')


class ArticleDetailAppSeializer(serializers.ModelSerializer):
    thumbnail = serializers.SerializerMethodField(read_only=True)
    author = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%Y-%m-%d', read_only=True)
    is_like = serializers.SerializerMethodField()
    is_collect = serializers.SerializerMethodField()

    def get_is_collect(self, obj):
        user = self.context['request'].user
        if user.is_anonymous:
            return False
        return MemberRecord.is_collect(obj, user.member)

    def get_is_like(self, obj):
        user = self.context['request'].user
        if user.is_anonymous:
            return False
        return MemberRecord.is_like(obj, user.member)

    def get_author(self, obj):
        return MemeberInfoAppSerializer(instance=obj.user.member).data

    def get_thumbnail(self, obj):
        if obj.thumbnail:
            return obj.thumbnail.get_url()
        return ''

    class Meta:
        model = Article
        fields = (
            'id', 'is_like', 'is_collect', 'title', 'describe', 'thumbnail', 'tags', 'author', 'content', 'brown_count',
            'like_count', 'create_time')
